
CREATE  procedure p_finastunwritemsfixast (
  @iyear integer,
  @imonth integer,
  @iastid integer  
) 

as  
  set nocount on
  declare @icount integer
  declare @iprioryear integer
  declare @ipriormonth integer
  declare @iprior2year integer
  declare @iprior2month integer

  declare @dpbmsrcamt decimal(18,2)
  declare @dptmincsrcamt decimal(18,2)
  declare @dptmdecsrcamt decimal(18,2)
  declare @dpdeprrate decimal(18,2)
  declare @isumdprmonth integer
  declare @dptmincdpramt decimal(18,2)
  declare @dptmdecdpramt decimal(18,2)
  declare @dpydpramt decimal(18,2)
  declare @dptmdpramt decimal(18,2)
  declare @dpbmdpramt decimal(18,2)
       
begin
  if (@imonth=1) 
  begin
    set @iprioryear = @iyear - 1
    set @ipriormonth = 12
  end
  else
  begin
    set @iprioryear = @iyear
    set @ipriormonth = @imonth - 1
  end
  select @icount=count(fixedassetid) from tft_msfixedassets
    where fixedassetid=@iastid and nyear=@iprioryear and nmonth=@ipriormonth

  if (@icount<1) 
    return

  if (@imonth<=2) 
  begin
    set @iprior2year = @iyear - 1
    set @iprior2month = 12 - 2 + @imonth
  end
  else
  begin
    set @iprior2year = @iyear
    set @iprior2month = @imonth - 2
  end
  select @icount=count(deprrate) from tft_msfixedassets
    where fixedassetid=@iastid and nyear=@iprior2year and nmonth=@iprior2month

  if (@icount>0) 
  begin
    select @dpbmsrcamt=bmsrcamt,@dptmincsrcamt=tmincsrcamt,@dptmdecsrcamt=tmdecsrcamt,
           @dpdeprrate=deprrate,@isumdprmonth=sumdprmonth,@dptmincdpramt=tmincdpramt,
           @dptmdecdpramt=tmdecdpramt,@dpydpramt=ydpramt,@dptmdpramt=tmdpramt,@dpbmdpramt=bmdpramt
      from  tft_msfixedassets
      where fixedassetid=@iastid and nyear=@iprior2year and nmonth=@iprior2month

    update tft_msfixedassets set bmsrcamt=@dpbmsrcamt+@dptmincsrcamt-@dptmdecsrcamt,
                                bmdpramt=@dpbmdpramt+@dptmincdpramt-@dptmdecdpramt,
                                ydpramt=@dpydpramt,
                                tmincsrcamt=@dptmincsrcamt,tmdecsrcamt=@dptmdecsrcamt,
                                sumdprmonth=@isumdprmonth,
                                tmincdpramt=@dptmincdpramt,tmdecdpramt=@dptmdecdpramt,
                                tmdpramt=0,deprrate=0,needfresh=1    
      where fixedassetid=@iastid and nyear=@iprioryear and nmonth=@ipriormonth
  end
  else
  begin
    select @dpbmsrcamt=startrawamt,@dpbmdpramt=startsumdepramt,@dpydpramt=startsumdepramt
      from tfb_fixedassets where fixedassetid=@iastid

    update tft_msfixedassets set bmsrcamt=@dpbmsrcamt, bmdpramt=@dpbmdpramt,ydpramt=@dpydpramt
      where fixedassetid=@iastid and nyear=@iprioryear and nmonth = @ipriormonth
  end
end



GO
